#! /usr/bin/python3 python3
# -*- coding: utf-8 -*-

# *************************************************************
#  Projectname @  pysm
#     Filename @  AdminController.py
#       Author @  Steve.ma
#  Create date @  2018/9/2
#  Description @  
# *************************************************************

from Library.Sm import *
from flask import render_template, abort, request
from jinja2 import TemplateNotFound
from Library.Cache import *
import json


class ApiControllerModel(SMClass) :
    Module = 'Api'
    Controller = None
    Action = None

    #redis缓存对象
    RedisObj = None

    Tools = None
    returnType = 'json'
    HproseParams = None

    def __init__(self):
        return

    # 获取接口get传参
    def get(self, name, default=None):
        if self.returnType == 'hprose' :
            if name in self.HproseParams:
                return self.HproseParams[name]
            else :
                return default
        return request.args.get(name, default=default)

    # 获取接口所有的get传参
    def getAll(self):
        if self.returnType == 'hprose' :
            return self.HproseParams
        return request.args

    # 获取接口post传参
    def post(self, name, default=None):
        if self.returnType == 'hprose' :
            if name in self.HproseParams:
                return self.HproseParams[name]
            else :
                return default
        return request.form.get(name, default=default)

    # 获取request Files 对象
    def getFiles(self):
        return request.files

    # 获取接口所有的post传参
    def postAll(self):
        if self.returnType == 'hprose' :
            return self.HproseParams
        return request.form

    # 设置缓存
    def setCache(self, name, value, ex=None):
        if self.RedisObj == None:
            self.RedisObj = SMCache()
        return self.RedisObj.setCache(name, json.dumps(value), ex)

    # 获取缓存
    def getCache(self, name):
        if self.RedisObj == None:
            self.RedisObj = SMCache()
        return self.RedisObj.getCache(name)

    # 删除缓存
    def removeCache(self, name):
        if self.RedisObj == None:
            self.RedisObj = SMCache()
        return self.RedisObj.removeCache(name)

    # 判断缓存是否存在
    def issetCache(self, name):
        if self.RedisObj == None:
            self.RedisObj = SMCache()
        return self.RedisObj.issetCache(name)

    def setReturnType(self, type = 'json'):
        self.returnType = type
        return

    # 页面实例化
    def showPage(self, page_template='', **context):
        try :
            return render_template('%s/%s.html' % (self.Controller, page_template), **context)
        except TemplateNotFound :
            return abort(404)

    # 页面展示
    def show(self, page='', **context):
        return self.showPage(page, **context)

    # Hprose访问接口时设置传过来的参数
    def setHproseParams(self, params=None):
        if 'isHprose' in params:
            self.setReturnType("hprose")
            self.HproseParams = params
        else :
            self.setReturnType("json")
            self.HproseParams = None

    # 调用Hprose用到的参数处理
    def getHproseParams(self, params):
        params['isHprose'] = True
        return params

    # 接口返回参数
    def returnMsg(self, status, data):
        if status :
            arr = {
                'status'    : str('success'),
                'code'      : int(0),
                'data'      : dict(data),
                'message'   : str('')
            }
        else :
            arr = {
                'status': str('error'),
                'code': int(data['code']),
                'data': dict({}),
                'message': str(data['message'])
            }

        if self.returnType == 'json' :
            return json.dumps(arr)
        elif self.returnType == 'xml' :
            return self.Tools.dict_to_xml(arr)
        elif self.returnType == 'jsonp' :
            return arr
        elif self.returnType == 'text' :
            return arr
        elif self.returnType == 'hprose' :
            return arr['data']
